/*
     Copyright 2007 Joseph M. Ferner

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using System;
using System.Collections.Generic;
using OpenServers.Net.Common.Listener;
using OpenServers.Net.Common.Socket;
using OpenServers.Net.Common.State;

namespace OpenServers.Net.Common {
    /// <summary>
    /// abstract class making it easier for implementers of <see cref="IServer"/>.
    /// </summary>
    public abstract class AbstractServer : IServer {
        private readonly IList<IListener> _listeners = new List<IListener>();
        private bool _started;

        /// <summary>
        /// Starts the server.
        /// </summary>
        public void Start() {
            foreach (IListener listener in _listeners) {
                listener.Start(this);
            }
            _started = true;
        }

        /// <summary>
        /// Stops the servers.
        /// </summary>
        public void Stop() {
            foreach (IListener listener in _listeners) {
                listener.Stop();
            }
            _started = false;
        }

        /// <summary>
        /// Gets the list of listeners.
        /// </summary>
        public IList<IListener> Listeners {
            get { return _listeners; }
        }

        /// <summary>
        /// Checks if server is started.
        /// </summary>
        public bool Started {
            get { return _started; }
        }


        /// <summary>
        /// Creates a state object.
        /// </summary>
        /// <param name="listener">the listener who called this method.</param>
        /// <param name="clientSocket">The client socket.</param>
        /// <returns></returns>
        public abstract IState CreateState(IListener listener, ISocket clientSocket);

        /// <summary>
        /// Initializes the state object.
        /// </summary>
        public event InitializeStateDelegate InitializeState;

        /// <summary>
        /// Fires the initialize state events.
        /// </summary>
        public void FireInitializeState(IState state) {
            if (InitializeState != null) {
                InitializeState(this, state);
            }
        }
    }
}
